package com.fc.push.handler.pub.verify;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fc.commons.security.MD5Util;
import com.fc.persistence.cache.ConstKey;
import com.fc.persistence.cache.redis.SharedJedisFacade;
import com.fc.persistence.dao.DAOTemplate;
import com.fc.push.GlobalServerConst;
import com.fc.push.db.TranscationFacade;
import com.fc.push.db.entities.Application;
import com.fc.push.handler.AbstractHttpHandler;
import com.fc.push.handler.HandlerResult;
import com.fc.push.handler.pub.MessageRCode;
import com.fc.push.handler.pub.service.APNsPublishUtil;
import com.fc.push.handler.pub.service.GlobalService;
import com.fc.push.handler.pub.service.MqttPublishUtil;
import com.fc.push.handler.pub.service.RedisServiceUtil;
import com.fc.push.mqtt.MqttConfig;
import com.fc.remoting.anno.Protocol;
import com.fc.remoting.core.SessionManager;

@Component
@Protocol(module = VerifyConst.VERIFY_MODULE_ID, order = VerifyConst.ORDER_2)
public class PublishServiceRegisterHandler extends AbstractHttpHandler {
	private static final String APPKEY = "appkey";
	private static final String PLATFORM = "platform";
	private static final String TOKEN = "token";
	private static final String TAG = "tag";
	private static final String DEVICE_ID = "device_id";
	private static final String CODE = "code";

	private static final String CLIENT_ID = "clientid";

	@Autowired
	APNsPublishUtil apnsPublishUti;
	
	@Autowired
	MqttPublishUtil mqttPublishUtil;
	
	@Autowired 
	RedisServiceUtil redisServiceUtil;
	
	@Autowired 
	GlobalService globalService;
	
	
	
	@Override
	public Object handle(HttpServletResponse response, JSONObject request) {
		String appkey = request.getString(APPKEY);
		String platform = request.getString(PLATFORM);

		JSONObject result = null;
		if (platform == null || platform.isEmpty()) {
			JSONObject object = HandlerResult.result();
			object.put(CODE, MessageRCode.RCODE_ERROR_1002);
			return object;
		}
		platform = platform.toLowerCase();

		String sql = "from " + Application.class.getSimpleName() + " where appkey = '" + appkey + "'";
		List<DAOTemplate> res = TranscationFacade.getInstance().transcation().getBySQL(sql);
		if (res == null || res.size() == 0) {
			JSONObject object = HandlerResult.result();
			object.put(CODE, MessageRCode.RCODE_ERROR_1008);
			return object;
		}
		Application application = (Application) res.get(0);

		// 平台标识不符合
		if (!application.getPlatform().toLowerCase().equals(platform)) {
			JSONObject object = HandlerResult.result();
			object.put(CODE, MessageRCode.RCODE_ERROR_1004);
			return object;
		}

		String token = null;
		result = HandlerResult.result();

		String clientid = null;
		if (platform.equals(GlobalServerConst.IOS)) {
			// 生成客户端id
			token = request.getString(TOKEN);
			clientid = apnsPublishUti.assClientId(appkey, token);

			// jedis.sadd(clientid, token);

			result.put("skey", MqttConfig.getUsername());
			result.put("svalue", MqttConfig.getPassword());
			result.put("ip", MqttConfig.getHost());
			result.put("post", MqttConfig.getPort());
			// 注册全局Tag
			globalService.registerGlobalInTag(platform, appkey, token);
		} else if (platform.equals(GlobalServerConst.ANDROID)) {
			String deviceid = request.getString(DEVICE_ID);
			clientid = mqttPublishUtil.assClientId(appkey, deviceid);

			// jedis.sadd(clientid, clientid);

			result.put("skey", MqttConfig.getUsername());
			result.put("svalue", MqttConfig.getPassword());
			result.put("ip", MqttConfig.getHost());
			result.put("post", MqttConfig.getPort());
			// 注册全局Tag
			globalService.registerGlobalInTag(platform, appkey, clientid);
		} else if (platform.equals(GlobalServerConst.WEB) || platform.equals(GlobalServerConst.H5)) {
			clientid = MD5Util.Instance.getInstance().md5TO23Bit(appkey);
			SessionManager.putHttpChannel(clientid, response);
			// 注册全局Tag
			globalService.registerGlobalInTag(platform, appkey, clientid);
		}
		result.put(CLIENT_ID, clientid);
		// 保存clientid到应用下面
		SharedJedisFacade.saddProxy(appkey, clientid);

		JSONArray tags = request.getJSONArray(TAG);
		Object[] objects = null;
		if (tags == null || tags.size() == 0) {
			return result;
		}
		objects = tags.toArray();
		if (platform.equals(GlobalServerConst.IOS)) {
			for (Object object : objects) {
				String ioskey = ConstKey.IOS_APP_SET_TAG.replaceFirst("APP", appkey);
				SharedJedisFacade.saddProxy(ioskey, object.toString());

				// 保存token到对应应用tag下面的token表
				globalService.registerInTag(ConstKey.IOS_APP_TAG_SET_TOKENS, appkey, object, token);
			}
		} else if (platform.equals(GlobalServerConst.ANDROID)) {
			for (Object object : objects) {
				String ankey = ConstKey.AN_APP_SET_TAG.replaceFirst("APP", appkey);
				SharedJedisFacade.saddProxy(ankey, object.toString());
				// 保存clientid到对应应用tag下面的clientid表
				globalService.registerInTag(ConstKey.AN_APP_TAG_SET_IDS, appkey, object, clientid);
			}
		} else if (platform.equals(GlobalServerConst.WEB)) {
			for (Object object : objects) {
				String webkey = ConstKey.WEB_APP_SET_TAG.replaceFirst("APP", appkey);
				SharedJedisFacade.saddProxy(webkey, object.toString());

				// 保存clientid到对应应用tag下面的clientid表
				globalService.registerInTag(ConstKey.WEB_APP_TAG_SET_IDS, appkey, object, clientid);
			}
		}

		result.put(TAG, tags);
		return result;
	}
}
